<template>
  <div class="advanced-search">
    <!-- 搜索按钮和当前条件显示 -->
    <div class="search-header">
      <div class="search-button-container">
        <!-- 放在左边 -->
        <div>
          <el-badge
              :value="activeConditionsCount||''"
              class="condition-badge"
          >
            <el-button
                type="primary"
                @click="toggleSearchPanel"
                @mouseenter="handleButtonMouseEnter"
                @mouseleave="handleButtonMouseLeave"
                :icon="Search"
                ref="searchButtonRef"
            >
              高级搜索

            </el-button>
          </el-badge>

          <!-- 刷新 -->
          <el-button
              style="margin-left: 12px"
              :icon="Refresh"
              @click="executeSearch"
          >
            刷新
          </el-button>

          <!-- 缓存当前查询条件 -->
          <el-button
              :icon="Plus"
              @click="saveCurrentConditions"
              :disabled="activeConditionsCount === 0"
          >
            缓存当前查询条件
          </el-button>

          <!-- 同步查询条件 -->
          <el-dropdown style="margin-left: 12px" @command="loadSavedConditions" :disabled="savedConditionsList.length === 0">
            <el-button>
              同步查询条件
              <el-icon class="el-icon--right">
                <arrow-down/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                    v-for="(item, index) in savedConditionsList"
                    :key="index"
                    :command="index"
                    class="saved-condition-item"
                >
                  <div class="condition-item-content">
                    <span class="condition-name">{{ item.name }}</span>
                    <span class="condition-count">({{ item.conditions.length }}个条件)</span>
                    <el-button
                        type="text"
                        size="small"
                        @click.stop="deleteSavedCondition(index)"
                        class="delete-btn"
                    >
                      删除
                    </el-button>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 悬浮的查询条件显示 -->
          <div
              v-if="activeConditionsCount > 0 && showFloatingConditions && !showSearchPanel"
              class="floating-conditions"
              :class="{ 'show-above': showConditionsAbove }"
              @mouseenter="handleFloatingMouseEnter"
              @mouseleave="handleFloatingMouseLeave"
          >
            <div class="conditions-header">
              <span class="conditions-title">查询条件：</span>
              <el-button
                  type="text"
                  size="small"
                  @click="clearAllConditions"
                  class="clear-all-btn"
              >
                清空所有
              </el-button>
            </div>
            <div class="conditions-content">
              <el-tag
                  v-for="(condition, index) in activeConditions"
                  :key="index"
                  closable
                  @close="removeCondition(index)"
                  class="condition-tag"
                  effect="light"
              >
                {{ getConditionText(condition) }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 放在右边 -->
        <div>
          <!-- 额外按钮  -->
          <slot name="extraButtons"/>
        </div>
      </div>
    </div>
    
    <!-- 高级搜索面板 -->
    <el-collapse-transition>
      <div v-show="showSearchPanel" class="search-panel">
        <el-card shadow="never">
          <div class="search-conditions">
            <!-- 搜索条件列表 -->
            <div 
              v-for="(condition, index) in searchConditions" 
              :key="index" 
              class="condition-row"
            >
              <!-- 字段选择 -->
              <el-select
                v-model="condition.field"
                placeholder="选择字段"
                class="field-select"
                @change="onFieldChange(condition)"
              >
                <el-option
                  v-for="field in availableFields"
                  :key="field.key"
                  :label="field.label"
                  :value="field.key"
                />
              </el-select>
              
              <!-- 操作符选择 -->
              <el-select
                v-model="condition.operator"
                placeholder="操作符"
                class="operator-select"
              >
                <el-option
                  v-for="op in getAvailableOperators(condition.field)"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </el-select>
              
              <!-- 值输入 -->
              <div class="value-input">
                <!-- 文本输入 -->
                <el-input
                  v-if="getFieldType(condition.field) === 'text'"
                  v-model="condition.value"
                  :placeholder="condition.placeholder||'请输入值'"
                  clearable
                />
                <!-- 数字输入 -->
                <el-input-number
                  v-else-if="getFieldType(condition.field) === 'number'"
                  v-model="condition.value"
                  placeholder="请输入数字"
                  style="width: 100%"
                />
                
                <!-- 日期选择 -->
                <el-date-picker
                  v-else-if="getFieldType(condition.field) === 'date'"
                  v-model="condition.value"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
                
                <!-- 日期时间选择 -->
                <el-date-picker
                  v-else-if="getFieldType(condition.field) === 'datetime'"
                  v-model="condition.value"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
                
                <!-- 下拉选择 -->
                <el-select
                  v-else-if="getFieldType(condition.field) === 'select'"
                  v-model="condition.value"
                  placeholder="请选择"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="option in getFieldOptions(condition.field)"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </div>

              <!-- 操作符选择 -->
              <el-select
                  v-if="activeConditionsCount > 1"
                  v-model="logicOperator"
                  placeholder="操作符"
                  class="operator-select"
              >
                <el-option label="且" value="AND" key="AND"/>
                <el-option label="或" value="OR" key="OR"/>
              </el-select>
              <!-- 删除条件按钮 -->
              <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="removeSearchCondition(index)"
              />
            </div>
            

          </div>
          
          <!-- 操作按钮 -->
          <div class="search-actions">
            <!-- 添加条件按钮 -->
              <el-button
                  :icon="Plus"
                  @click="addSearchCondition"
              >
                添加条件
              </el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="executeSearch">搜索</el-button>
          </div>
        </el-card>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { SearchField, SearchOperator, SearchCondition, SavedConditionGroup } from '@/types/search'
import { AdvancedSearchManager } from './index'

// 定义接口
interface SearchField {
  key: string
  label: string
  type: 'text' | 'number' | 'date' | 'datetime' | 'select'
  options?: Array<{ label: string; value: any }>
}

interface SearchOperator {
  value: string
  label: string
  types: string[] // 支持的字段类型
}

interface SearchCondition {
  field: string
  operator: string
  value: any
  placeholder:string
}

interface SavedConditionGroup {
  name: string
  conditions: SearchCondition[]
  logic: 'AND' | 'OR'
  createdAt: number
}

// Props
interface Props {
  fields: SearchField[]
  modelValue?: SearchCondition[]
}

const props = withDefaults(defineProps<Props>(), {
  fields: () => [],
  modelValue: () => []
})

// Emits
interface Emits {
  (e: 'update:modelValue', value: SearchCondition[]): void
  (e: 'search', conditions: SearchCondition[]): void
  (e: 'reset'): void
}

const emit = defineEmits<Emits>()

// 路由和用户信息
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const showSearchPanel = ref(false)
const showFloatingConditions = ref(false)
const searchConditions = ref<SearchCondition[]>([{ field: '', operator: '', value: '' }])
const searchButtonRef = ref()
const showConditionsAbove = ref(false)
const logicOperator = ref<'AND' | 'OR'>('AND')
const savedConditionsList = ref<SavedConditionGroup[]>([])
let hideTimer: NodeJS.Timeout | null = null

// 可用的操作符
const operators: SearchOperator[] = [
  { value: 'eq', label: '等于', types: ['text', 'number', 'date', 'datetime', 'select'] },
  { value: 'ne', label: '不等于', types: ['text', 'number', 'date', 'datetime', 'select'] },
  { value: 'like', label: '包含', types: ['text'] },
  { value: 'notLike', label: '不包含', types: ['text'] },
  { value: 'likeLeft', label: '以...开头', types: ['text'] },
  { value: 'likeRight', label: '以...结尾', types: ['text'] },
  { value: 'gt', label: '大于', types: ['number', 'date', 'datetime'] },
  { value: 'ge', label: '大于等于', types: ['number', 'date', 'datetime'] },
  { value: 'lt', label: '小于', types: ['number', 'date', 'datetime'] },
  { value: 'le', label: '小于等于', types: ['number', 'date', 'datetime'] },
  { value: 'in', label: '在范围内', types: ['text', 'number', 'select'] },
  { value: 'notIn', label: '不在范围内', types: ['text', 'number', 'select'] },
  { value: 'isNull', label: '为空', types: ['text', 'number', 'date', 'datetime'] },
  { value: 'isNotNull', label: '不为空', types: ['text', 'number', 'date', 'datetime'] }
]

// 计算属性
const availableFields = computed(() => {
  return props.fields
})

const activeConditions = computed(() => {
  return searchConditions.value.filter(condition => 
    condition.field && condition.operator && 
    (condition.value !== '' && condition.value !== null && condition.value !== undefined)
  )
})

const activeConditionsCount = computed(() => activeConditions.value.length)

// 鼠标事件处理方法
const handleButtonMouseEnter = () => {
  if (hideTimer) {
    clearTimeout(hideTimer)
    hideTimer = null
  }
  showFloatingConditions.value = true
}

const handleButtonMouseLeave = () => {
  hideTimer = setTimeout(() => {
    showFloatingConditions.value = false
  }, 200) // 200ms延迟
}

const handleFloatingMouseEnter = () => {
  if (hideTimer) {
    clearTimeout(hideTimer)
    hideTimer = null
  }
  showFloatingConditions.value = true
}

const handleFloatingMouseLeave = () => {
  hideTimer = setTimeout(() => {
    showFloatingConditions.value = false
  }, 200) // 200ms延迟
}

// 方法
const toggleSearchPanel = () => {
  showSearchPanel.value = !showSearchPanel.value
}

const getFieldType = (fieldKey: string): string => {
  const field = availableFields.value.find(f => f.key === fieldKey)
  return field?.type || 'text'
}

const getFieldOptions = (fieldKey: string) => {
  const field = availableFields.value.find(f => f.key === fieldKey)
  return field?.options || []
}

const getAvailableOperators = (fieldKey: string) => {
  const fieldType = getFieldType(fieldKey)
  return operators.filter(op => op.types.includes(fieldType))
}

const onFieldChange = (condition: SearchCondition) => {
  // 重置操作符和值
  condition.operator = ''
  condition.value = ''
  
  // 设置placeholder
  const field = availableFields.value.find(f => f.key === condition.field)
  condition.placeholder = field?.placeholder || '请输入值'
  
  // 如果字段有可用操作符，自动选择第一个
  const availableOps = getAvailableOperators(condition.field)
  if (availableOps.length > 0) {
    condition.operator = availableOps[0].value
  }
}

const addSearchCondition = () => {
  searchConditions.value.push({ field: '', operator: '', value: '' })
}

const removeSearchCondition = (index: number) => {
  if (searchConditions.value.length > 1) {
    searchConditions.value.splice(index, 1)
  } else {
    // 如果只有一个条件，重置它
    searchConditions.value[0] = { field: '', operator: '', value: '' }
  }
}

const removeCondition = (index: number) => {
  const activeIndex = searchConditions.value.findIndex((condition, i) => {
    const isActive = condition.field && condition.operator && 
      (condition.value !== '' && condition.value !== null && condition.value !== undefined)
    return isActive && activeConditions.value.indexOf(condition) === index
  })
  
  if (activeIndex !== -1) {
    removeSearchCondition(activeIndex)
  }
}

const clearAllConditions = () => {
  searchConditions.value = [{ field: '', operator: '', value: '' }]
  emit('update:modelValue', [])
  emit('reset')
}

// 检测悬浮条件显示位置
const checkConditionsPosition = () => {
  if (!searchButtonRef.value) return
  
  const buttonRect = searchButtonRef.value.$el.getBoundingClientRect()
  const viewportHeight = window.innerHeight
  const spaceBelow = viewportHeight - buttonRect.bottom
  const spaceAbove = buttonRect.top
  
  // 如果下方空间不足300px，则显示在上方
  showConditionsAbove.value = spaceBelow < 300 && spaceAbove > 200
}

// 窗口大小改变时重新检测位置
const handleResize = () => {
  checkConditionsPosition()
}

// 生命周期
onMounted(() => {
  window.addEventListener('resize', handleResize)
  loadSavedConditionsFromStorage()
  nextTick(() => {
    checkConditionsPosition()
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const resetSearch = () => {
  clearAllConditions()
}

const executeSearch = () => {
  const validConditions = activeConditions.value
  const searchQuery = {
    conditions: validConditions,
    logic: logicOperator.value
  }
  emit('update:modelValue', validConditions)
  emit('search', searchQuery)
  // showSearchPanel.value = false
}

const getConditionText = (condition: SearchCondition): string => {
  const field = availableFields.value.find(f => f.key === condition.field)
  const operator = operators.find(op => op.value === condition.operator)
  const fieldLabel = field?.label || condition.field
  const operatorLabel = operator?.label || condition.operator
  
  let valueText = condition.value
  if (field?.type === 'select' && field.options) {
    const option = field.options.find(opt => opt.value === condition.value)
    valueText = option?.label || condition.value
  }
  
  return `${fieldLabel} ${operatorLabel} ${valueText}`
}

// 缓存相关方法
const loadSavedConditionsFromStorage = () => {
  try {
    const userId = userStore.userInfo?.userId || 'anonymous'
    const pagePath = route.path
    savedConditionsList.value = AdvancedSearchManager.loadSavedConditions(userId,pagePath)
    // 如果有保存的条件且当前没有活动条件，自动加载最新的一个
    if (savedConditionsList.value.length > 0 && activeConditionsCount.value === 0) {
      const latest = savedConditionsList.value[savedConditionsList.value.length - 1]
      loadConditionGroup(latest)
    }
  } catch (error) {
    console.error('加载保存的查询条件失败:', error)
  }
}

const saveSavedConditionsToStorage = () => {
  try {
    const userId = userStore.userInfo?.userId || 'anonymous'
    const pagePath = route.path
    AdvancedSearchManager.saveSavedConditions(savedConditionsList.value, userId, pagePath)
  } catch (error) {
    console.error('保存查询条件失败:', error)
    ElMessage.error('保存查询条件失败')
  }
}

const generateConditionGroupName = (): string => {
  const count = savedConditionsList.value.length + 1
  return `查询分组 ${count}`
}

const saveCurrentConditions = async () => {
  if (activeConditionsCount.value === 0) {
    ElMessage.warning('没有可保存的查询条件')
    return
  }

  try {
    const { value: customName } = await ElMessageBox.prompt(
      '请输入查询条件组名称（可选）',
      '保存查询条件',
      {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPlaceholder: generateConditionGroupName()
      }
    )

    const groupName = customName?.trim() || generateConditionGroupName()
    
    const newGroup: SavedConditionGroup = {
      name: groupName,
      conditions: [...activeConditions.value],
      logic: logicOperator.value,
      createdAt: Date.now()
    }

    savedConditionsList.value.push(newGroup)
    saveSavedConditionsToStorage()
    
    ElMessage.success(`查询条件已保存为"${groupName}"`)
  } catch (error) {
    // 用户取消操作
  }
}

const loadConditionGroup = (group: SavedConditionGroup, triggerSearch = false) => {
  searchConditions.value = [...group.conditions]
  logicOperator.value = group.logic
  
  // 确保至少有一个空条件用于添加新条件
  if (!searchConditions.value.some(c => !c.field)) {
    searchConditions.value.push({ field: '', operator: '', value: '' })
  }
  
  // 通知父组件更新modelValue，确保查询条件能够渲染
  emit('update:modelValue', activeConditions.value)
  
  // 只有在明确要求触发搜索时才触发搜索事件
  if (triggerSearch && activeConditions.value.length > 0) {
    emit('search', {
      conditions: activeConditions.value,
      logic: logicOperator.value
    })
  }
}

const loadSavedConditions = (index: number) => {
  if (index >= 0 && index < savedConditionsList.value.length) {
    const group = savedConditionsList.value[index]
    loadConditionGroup(group, true) // 用户手动选择时触发搜索
    ElMessage.success(`已加载查询条件"${group.name}"`)
  }
}

const deleteSavedCondition = async (index: number) => {
  if (index >= 0 && index < savedConditionsList.value.length) {
    const group = savedConditionsList.value[index]
    
    try {
      await ElMessageBox.confirm(
        `确定要删除查询条件"${group.name}"吗？`,
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      savedConditionsList.value.splice(index, 1)
      saveSavedConditionsToStorage()
      ElMessage.success('查询条件已删除')
    } catch (error) {
      // 用户取消操作
    }
  }
}



// 监听外部传入的值
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && newValue.length > 0) {
      searchConditions.value = [...newValue]
      // 确保至少有一个空条件用于添加新条件
      if (!searchConditions.value.some(c => !c.field)) {
        searchConditions.value.push({ field: '', operator: '', value: '' })
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听活动条件变化，重新检测位置
watch(
  () => activeConditionsCount.value,
  () => {
    nextTick(() => {
      checkConditionsPosition()
    })
  }
)
</script>

<style scoped>
.advanced-search {
  margin-bottom: 16px;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.search-header .el-button {
  margin-right: 0;
}

.search-header .el-dropdown .el-button {
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
}

.search-header .el-dropdown .el-button:hover {
  border-color: #c0c4cc;
}

.search-header .el-dropdown .el-button:focus {
  border-color: #409eff;
  outline: none;
}

.search-button-container {
  position: relative;
  display: inline-block;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.condition-badge {
  margin-left: 8px;
}

.floating-conditions {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  min-width: 300px;
  max-width: 600px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 12px;
}

.floating-conditions.show-above {
  top: auto;
  bottom: calc(100% + 8px);
}

.conditions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.conditions-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.conditions-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.condition-tag {
  margin: 0;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
}

.clear-all-btn {
  color: #909399;
  padding: 0;
  font-size: 12px;
}

.search-panel {
  margin-bottom: 16px;
}

.search-conditions {
  margin-bottom: 16px;
}

.condition-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.field-select {
  width: 150px;
}

.operator-select {
  width: 120px;
}

.value-input {
  flex: 1;
  min-width: 200px;
}

.add-condition {
  text-align: center;
  padding: 12px 0;
  border-top: 1px dashed #dcdfe6;
}

.search-actions {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 删除按钮动画 */
.condition-row .el-button--danger {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.condition-row .el-button--danger:hover {
  transform: translateY(-2px) scale(1.1);
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.3);
}

/* 缓存相关样式 */
.saved-condition-item {
  padding: 0;
}

.condition-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  width: 100%;
}

.condition-name {
  font-weight: 500;
  color: #303133;
  flex: 1;
}

.condition-count {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.delete-btn {
  color: #f56c6c;
  margin-left: 8px;
  padding: 0 4px;
}

.delete-btn:hover {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .condition-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .field-select,
  .operator-select,
  .value-input {
    width: 100%;
  }
}
</style>